<?php
namespace App\Admin\Controllers\Basics;

use App\Models\Basics\SupplierM;
use App\Models\Product\ProductSupplierM;
use Encore\Admin\Controllers\AdminController;
use App\Models\Basics\SettlementMethod;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
class SupplierMController extends AdminController{

    protected $title = '材料供应商';

    protected function grid()
    {
        $grid = new Grid(new SupplierM());

        $grid->model()->where('type',2)
            ->with(['supplier_contacts','supplier_account'])
            ->orderBy('id', 'DESC');

        $grid->column('id','ID')->style('width: 5%');
        $grid->column('code','编码')->sortable()->label();
        $grid->column('name','名称')->style('max-width:200px');
        $grid->column('short_name','简称')->style('max-width:150px');
        $grid->column('settlement_method.settlement_method','结算方式')->style('max-width:200px');
        $grid->column('main_product','主营产品')->style('max-width:200px');
        $grid->column('address','详细地址')->style('max-width:200px');
        $grid->column('联系方式')->expand(function ($model) {
            $contacts = $model->supplier_contacts->map(function($item){
                return collect($item)->except(['id','supplier_id']);
            })->toArray();
            return new Table(['联系人', '手机号', '职务', '座机号', 'QQ', '微信', '邮箱'], $contacts);
        });
        $grid->column('银行资料')->expand(function ($model) {
            $account = collect($model->supplier_account)->except(['id','supplier_id'])->toArray();
            return new Table(['开户行', '开户人', '银行卡号', '身份证号'], [$account]);
        });

        $grid->column('ship_fee_type','运费类型')->display(function ($value){
            return array_key_exists($value,SupplierM::$_shipFeeType) ? SupplierM::$_shipFeeType[$value] : '未知';
        })->filter(SupplierM::$_shipFeeType);

        $grid->column('tax','税点');
        $grid->column('audit_status','审核')->bool()->filter(SupplierM::$_auditStatus);
        $grid->column('status','启用')->bool([1 => true, 2 => false])->filter(SupplierM::$_status);
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
        });
        $grid->paginate(10);

        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->filter(function(Grid\Filter $filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->where('code', 'like', "%{$this->input}%")
                        ->orWhere('short_name', 'like', "%{$this->input}%")
                        ->orWhere('name', 'like', "%{$this->input}%")
                        ->orWhere('main_product', 'like', "%{$this->input}%")
                        ->orWhere('address', 'like', "%{$this->input}%");
                }, '查询')->placeholder('模糊查询编码，名称，主营产品，地址');
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('settlement_method_id','结算')->select(SettlementMethod::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('supplier_contacts', function ($query) {
                        $query->where('contact', 'like', "%{$this->input}%");
                    });
                }, '联系人');
            });
        });

        return $grid;
    }

    protected function detail($id)
    {
        $show = new Show(SupplierM::with(['settlement_method','supplier_contacts','material'])->findOrFail($id));
        $show->name('供应商名称');
        $show->short_name('供应商简称');
        $show->code('供应商编码');
        $show->field('settlement_method.settlement_method','结算方式');
        $show->main_product('主营产品');
        $show->address('详细地址');
        $show->remark('合同备注');
        $show->field('supplier_account.bank','开户行');
        $show->field('supplier_account.accounter','开户人');
        $show->field('supplier_account.bank_number','银行卡号');
        $show->field('supplier_account.identity_number','身份证号');
        $show->field('supplier_file.file','文件资料')->multipleFile();
        $show->panel()->title('基本信息');
        $show->panel()->tools(function (Show\Tools $tools) {
            $tools->disableDelete();
        });
        $show->supplier_contacts('联系方式', function ($supplierContacts) {
            $supplierContacts->contact('联系人');
            $supplierContacts->cellphone('手机号');
            $supplierContacts->position('职务');
            $supplierContacts->telephone('座机号');
            $supplierContacts->qq('QQ');
            $supplierContacts->we_chat('微信号');
            $supplierContacts->email('邮箱');
            $supplierContacts->disableActions();
            $supplierContacts->disablePagination();
            $supplierContacts->disableRowSelector();
            $supplierContacts->disableFilter();
            $supplierContacts->disableExport();
            $supplierContacts->disableCreation();
            $supplierContacts->disableColumnSelector();
        });

        $show->material('材料列表', function ($sku) {
            $sku->id('ID')->display(function ($value){
                return '<a href="/xqc/products/material-list/'.$value.'" target="_blank">'.$value.'</a >';
            });
            $sku->material_code('材料编码');
            $sku->title('材料名称');
            $sku->supplier_material_no('供应商材料编号')->display(function () {
                return $this->pivot->supplier_material_no;
            });
            $sku->quote_price('报价')->display(function () {
                return $this->pivot->quote_price;
            });
            $sku->purchase_cycle('报价单位')->display(function () {
                $value = $this->pivot->quote_currency ?? '';
                return $value ? ProductSupplierM::$_quote_currency[$value] : '';
            });
            $sku->audit_status('审核状态')->display(function (){
                $value = $this->pivot->audit_status ?? '';
                return $value ? ProductSupplierM::$_auditStatus[$value] : '';
            });
            $sku->audit_time('审核时间')->display(function () {
                return $this->pivot->audit_time;
            });
            $sku->disableActions();
            $sku->disableExport();
            $sku->paginate(10);
            $sku->disableRowSelector();
            $sku->disableFilter();
            $sku->disableCreation();
        });

        return $show;
    }

    protected function form()
    {
        $form = new Form(new SupplierM());

        $form->tab('基本信息', function (Form $form) {
            $form->text('code','供应商编码')
                ->creationRules(['required', "unique:b_supplier"])
                ->updateRules(['required', "unique:b_supplier,code,{{id}}"])->help('编码时以CL开头，和成品供应商共用编码，请勿与成品供应商重复使用');
            $form->text('name','供应商名称')->rules('required');
            $form->text('short_name','供应商简称')
                ->creationRules(['required', "unique:b_supplier"])
                ->updateRules(['required', "unique:b_supplier,short_name,{{id}}"])->help('和成品供应商共用简称，请勿与成品供应商重复使用');
            $form->select('settlement_method_id','结算方式')->options(SettlementMethod::options())->rules('required');
            $form->text('address','详细地址')->rules('required');
            $form->radio('ship_fee_type','运费类型')->options(SupplierM::$_shipFeeType)->rules('required');
            $form->number('tax','税点')->default(0)->rules('required');
            $form->text('main_product','主营产品')->rules('required');
            $form->text('remark','合同备注');
            $form->hidden('type')->default('2');
            if(Admin::user()->can('supplier.approval')){
                $form->radio('audit_status','审核')->options(SupplierM::$_auditStatus)->default('0')->rules('required');
            }else{
                $form->hidden('audit_status')->default('0');
            }
            $form->radio('status','启用')->options(SupplierM::$_status)->default('1')->rules('required');
        })->tab('银行资料', function (Form $form) {
            $form->text('supplier_account.bank','开户行');
            $form->text('supplier_account.accounter','开户人');
            $form->text('supplier_account.bank_number','银行卡号');
            $form->text('supplier_account.identity_number','身份证号');
        })->tab('文件资料', function (Form $form) {
            $form->multipleFile('supplier_file.file','上传文件')->removable()->downloadable();
        })->tab('联系方式', function (Form $form) {
            $form->hasMany('supplier_contacts','联系方式',function (Form\NestedForm $form){
                $form->text('contact','联系人');
                $form->text('cellphone','手机号');
                $form->text('position','职务');
                $form->text('telephone','座机号');
                $form->text('qq','QQ');
                $form->text('we_chat','微信');
                $form->text('email','邮箱');
            });
        });

        $form->tools(function (Form\Tools $tools){
            $tools->disableDelete();
        });

        return $form;
    }
}
